package com.jdrx.sw.sewage.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jdrx.ocp.beans.entity.UserPO;
import com.jdrx.ocp.dao.UserDAO;
import com.jdrx.sw.sewage.beans.dto.MessageSubscribeDTO;
import com.jdrx.sw.sewage.beans.dto.UnlimitedDTO;
import com.jdrx.sw.sewage.beans.vo.MessageSubscribeVO;
import com.jdrx.sw.sewage.common.constant.Constant;
import com.jdrx.sw.sewage.common.enums.MessagePush;
import com.jdrx.sw.sewage.common.enums.MessageSubscribeType;
import com.jdrx.sw.sewage.common.helper.HttpUtils;
import com.jdrx.sw.sewage.common.util.LocalDateTimeUtils;
import com.jdrx.sw.sewage.dao.MessageSubscribeDAO;
import com.jdrx.sw.sewage.dao.UserMessageSubscribeDAO;
import com.jdrx.sw.sewage.service.base.BaseServiceImpl;
import com.jdrx.sw.sewage.service.common.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class MessageSubscribeServiceImpl extends BaseServiceImpl {

    @Value("${weixin.host}")
    private String host;
    @Value("${weixin.minAppId}")
    private String minAppId;
    @Value("${weixin.minSecret}")
    private String minSecret;
    @Value("${weixin.minGrantType}")
    private String minGrantType;
    @Value("${weixin.mpAppId}")
    private String mpAppId;
    @Value("${weixin.url}")
    private String url;
    @Value("${weixin.alarmMpTemplateId}")
    private String alarmMpTemplateId;
    @Value("${weixin.briefMpTemplateId}")
    private String briefMpTemplateId;
    @Value("${weixin.alarmPagePath}")
    private String alarmPagePath;
    @Value("${weixin.briefPagePath}")
    private String briefPagePath;
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private MessageSubscribeDAO messageSubscribeDAO;
    @Autowired
    private UserMessageSubscribeDAO userMessageSubscribeDAO;
    @Autowired
    private RedisService redisService;

    public List<MessageSubscribeVO> getList(Long uid, List<Long> stationIds) {
        return messageSubscribeDAO.getList(uid, stationIds);
    }

    //  https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
    public String getOpenId(String jsCode, Long uid) throws Exception {
        UserPO userPO = userDAO.getById(uid);
        String openid = userPO.getOpenId();
        if (StringUtils.isNotEmpty(openid)) return null;

        Map<String, String> headers = Maps.newHashMap();
        Map<String, String> querys = Maps.newHashMap();
        querys.put("appid", minAppId);
        querys.put("secret", minSecret);
        querys.put("js_code", jsCode);
        querys.put("grant_type", minGrantType);
        JSONObject jsonObject = HttpUtils.doGet(host, "/sns/jscode2session", headers, querys);//openid -> o-Gis5bjgF58bhqZZ5PhBmNZQZ7E
        Integer errcode = jsonObject.getInteger("errcode");
        if (null != errcode && !errcode.equals(0)) return jsonObject.getString("errmsg");
        openid = jsonObject.getString("openid");

        UserPO po = new UserPO();
        po.setId(uid);
        po.setOpenId(openid);
        userDAO.update(po);
        return null;
    }

    // GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
    public String getAccessToken() throws Exception {
        String accessToken = redisService.getStr(Constant.WX_ACCESS_TOKEN + minAppId);
        if (StringUtils.isNotEmpty(accessToken)) return accessToken;

        JSONObject jsonObject = HttpUtils.doGet(host, "/cgi-bin/token?grant_type=client_credential&appid=" + minAppId + "&secret=" + minSecret, Maps.newHashMap(), Maps.newHashMap());
        Integer errcode = jsonObject.getInteger("errcode");
        if (null != errcode && !errcode.equals(0)) return jsonObject.getString("errmsg");

        String access_token = jsonObject.getString("access_token");
        redisService.set(Constant.WX_ACCESS_TOKEN + minAppId, access_token, 7140L);
        return access_token;
    }

    //  POST https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=ACCESS_TOKEN
    public String pushAlarm(String touser, Long alarmId, String alarmInfo, String title, String remark, Integer type) throws Exception {

        JSONObject body = new JSONObject();
        JSONObject mp_template_msg = new JSONObject();
        mp_template_msg.put("appid", mpAppId);
        mp_template_msg.put("url", url);

        JSONObject mini = new JSONObject();
        mini.put("appid", minAppId);

        JSONObject data = new JSONObject();
        JSONObject firstj = new JSONObject();
        JSONObject contentj = new JSONObject();
        JSONObject occurtimej = new JSONObject();
        JSONObject remarkj = new JSONObject();
        firstj.put("value", title);
        contentj.put("value", alarmInfo);
        occurtimej.put("value", LocalDateTimeUtils.localDateTime2String(LocalDateTime.now()));
        remarkj.put("value", remark);

        data.put("first", firstj);
        data.put("remark", remarkj);

        if (MessageSubscribeType.ALARM_EVENT_PUSH.getKey().equals(type)) {
            mp_template_msg.put("template_id", alarmMpTemplateId);
            mini.put("pagepath", alarmPagePath + alarmId);
            data.put("content", contentj);
            data.put("occurtime", occurtimej);
        }

        if (MessageSubscribeType.BRIEF_REPORT_PUSH.getKey().equals(type)) {
            mp_template_msg.put("template_id", briefMpTemplateId);
            mini.put("pagepath", briefPagePath);
            data.put("keyword1", contentj);
            data.put("keyword2", occurtimej);
        }

        mp_template_msg.put("data", data);
        mp_template_msg.put("miniprogram", mini);

        body.put("touser", touser);
        body.put("mp_template_msg", mp_template_msg);
        JSONObject jsonObject = HttpUtils.postJson(host + "/cgi-bin/message/wxopen/template/uniform_send?access_token=" + getAccessToken(), body.toString());

        Integer errcode = jsonObject.getInteger("errcode");
        if (null != errcode && !errcode.equals(0)) return jsonObject.getString("errmsg");
        return null;
    }

    //POST https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN
    public InputStream getUnlimited(UnlimitedDTO unlimitedDTO) throws Exception {
        JSONObject body = new JSONObject();
        body.put("scene", unlimitedDTO.getScene());
        body.put("page", unlimitedDTO.getPage());
        body.put("width", unlimitedDTO.getWidth());
        body.put("auto_color", unlimitedDTO.getAuto_color());
        body.put("line_color", unlimitedDTO.getLine_color());
        body.put("is_hyaline", unlimitedDTO.getIs_hyaline());
        return HttpUtils.postJsonResponse(host + "/wxa/getwxacodeunlimit?access_token=" + getAccessToken(), body.toString());
    }

    public void subscribe(List<MessageSubscribeDTO> dto) {
        dto.forEach(item -> {
            userMessageSubscribeDAO.deleteBySIdAndTypeAndUserId(item);
            if (MessagePush.subscribe_y.getKey().equals(item.getSubscribe())) {
                userMessageSubscribeDAO.addBySIdAndTypeAndUserId(item);
            }
        });
    }
}